import uuid
from flask import Blueprint, request, jsonify, current_app
from utils.logger import get_logger

logger = get_logger(__name__)

api = Blueprint('api', __name__, url_prefix='/api')


@api.route('/chat', methods=['POST'])
async def chat():
    try:
        logger.info("Received chat request")
        
        if request.json["id"] == "":
            id = str(uuid.uuid4())
            logger.info(f"Generated new session ID: {id}")
        else:
            id = request.json["id"]
            logger.info(f"Using existing session ID: {id}")
        
        logger.debug(f"Request data: {request.json}")
        
        chat_service = current_app.chat_service
        logger.info(f"Processing chat request for session {id}")
        
        response = await chat_service.solve(session_id=id, input_data=request.json)
        logger.info(f"Successfully processed chat request for session {id}")
        
        return response
    except Exception as e:
        error_msg = f"Error processing chat request: {str(e)}"
        logger.error(error_msg, exc_info=True)
        return jsonify({"error": str(e)}), 500

